<?php

class PlayerController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','file','index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','approve', 'revalidate'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	
	public function actions() {
		return array (
				
				'approve' => array ('class' => 'CViewAction'),
				
				'file' => array ('class' => 'CViewAction'),
				
				'revalidate' => array ('class' => 'CViewAction'),
		);
	}
	

	public function isRevalidated($player) {
		$history = History::model()->findByAttributes(array('player'=>$player->id, 'year'=>date('Y')));
		
		return $history != null;
	}
	
	public function actionApprove($id) {
		if(Yii::app()->request->isPostRequest) {
			$player = $this->loadModel($id);
			$player->status = 'ATIVO';
			
			echo '$player->id:'.$player->id;
echo '<br>$player->deferation:'.$player->federation_id;
echo '<br>$player->category_id:'.$player->category_id;
echo '<br>$player->name:'.$player->name;
echo '<br>$player->registry_date:'.$player->registry_date;
echo '<br>$player->natural_country:'.$player->natural_country;
echo '<br>$player->natural_state:'.$player->natural_state;
echo '<br>$player->city:'.$player->natural_city;
echo '<br>$player->nickname:'.$player->nickname;
echo '<br>$player->birthy_date:'.$player->birthy_date;
echo '<br>$player->gender:'.$player->gender;
echo '<br>$player->father_name:'.$player->father_name;
echo '<br>$player->mother_name:'.$player->mother_name;
echo '<br>$player->email:'.$player->email;
echo '<br>$player->address:'.$player->address;
echo '<br>$player->neighbor:'.$player->neightborhood;
echo '<br>$player->state:'.$player->state;
echo '<br>$player->city:'.$player->city;
echo '<br>$player->cert:'.$player->cert_birthy;
echo '<br>$player->rg:'.$player->rg;
echo '<br>$player->emissor:'.$player->emissor;
echo '<br>$player->validate:'.$player->doc_validate;
echo '<br>$player->cpf:'.$player->cpf;
echo '<br>$player->ctps:'.$player->ctps;
echo '<br>$player->cnh:'.$player->cnh;
echo '<br>$player->status:'.$player->status;
			$player->save();
			
			
			$history = new History;
			$history->history_date = date('Y-m-d');
			$history->player = $player->id;
			$history->year = date('Y');
			$history->observation = "AUTHENTICATION";
			$history->save();
			
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax'])){
				$this->redirect(array('view', 'id'=> $id));
			}
		} else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}
	
	public function actionRevalidate($id) {
		if(Yii::app()->request->isPostRequest) {
			$player = $this->loadModel($id);
			$player->status = 'ATIVO';
			$player->save();
				
			$history = new History;
			$history->history_date = date('Y-m-d');
			$history->player = $player->id;
			$history->year = date('Y');
			$history->observation = "REVALIDATION";
			$history->save();
				
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax'])){
				$this->redirect(array('view', 'id'=> $id));
			}
		} else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	
	public function actionFile($filename, $url) {
	
		return Yii::app()->getRequest()->sendFile($filename, @file_get_contents($url));
	}
	

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($team_id,$return_url)
	{
		
		if(!is_dir(Yii::getPathOfAlias('webroot').'/images')) {
			mkdir(Yii::getPathOfAlias('webroot').'/images');
			chmod(Yii::getPathOfAlias('webroot').'/images');//, 0755);
		}
		
		$model=new Player;
		$foto = array();
		$formats = 'jpg|gif|png|pdf|doc|odt|docx|xls|xlsx';
		$images = array();
		$file = new File();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Player']))
		{
			date_default_timezone_set('UTC');
			
			$model->attributes= $_POST['Player'];
			if($_SESSION['user']->username != 'admin') {
				$model->category_id = 0;
			}

			$images = CUploadedFile::getInstancesByName('filenames');
			
			$foto = CUploadedFile::getInstancesByName('foto');
			
 			$age = 0;
			
  			if($model->birthy_date != "") {
  				$age = Utils::getCategory($model->birthy_date);
  			}
 			
  			$model->registry_date = date("Y-m-d");
  			
  			$model->setBirthDate($model->birthy_date);
  			
  			if($model->validate() && $age != null && isset($images) && count($images) > 0 && isset($foto) && count($foto) > 0) {
 				
  				$id_team = $team_id;
  				
  				if($_SESSION['user']->username == 'admin') {
 					$id_team = $model->category_id;
 					$model->category_id = 0;
 					$model->status = "ATIVO";
 					
 					
 					
 				}
  				
 				$category = $this->saveCategory($model,$id_team, $age);
  				$model->category_id = $category->id;
 				
  				$model->save();
  				
 				foreach ($images as $image => $pic) {
 						
 					if(!empty($pic)) {
 						$pic->saveAs(Yii::getPathOfAlias('webroot').'/images/'.$pic->name);
 						// add it to the main model now
 						$file = new File();
 						$file->url = Yii::getPathOfAlias('webroot').'/images/'.$pic->name;
 						$file->filename = $pic->name;
 						$file->relation_id = $model->id; 
 						$file->type = "PLAYER";
 						$file->save();
 					}
 				}
 			
 				foreach($foto as $path => $pic) {
 					 
 					if(!empty($pic)) {
 						$extension = pathinfo($pic->name, PATHINFO_EXTENSION);
 						$pic->saveAs(Yii::getPathOfAlias('webroot') . '/images/' . Player::$photo_name . $model->id . '.' . $extension);
 						$file = new File();
 						$file->url = Yii::getPathOfAlias('webroot') . '/images/' . Player::$photo_name . $model->id .  '.' . $extension;
 						$file->filename = Player::$photo_name . $model->id .  '.' . $extension;
 						$file->relation_id = $model->id;
 						$file->type="PLAYER";
 						$file->save();
 					}
 				}
 				

 				if($_SESSION['user']->username == 'admin') {
 					$this->actionRevalidate($model->id);
 				}
 				
 				
  				$this->redirect(Yii::app()->request->baseUrl.'/index.php'. $return_url);
  			}
 			
 		}

		$this->render('create',array(
			'model'=>$model,
			'foto'=>$foto,
			'formats'=>$formats,
			'images'=>$images,
			'file'=>$file,
		));
	}

	
	public static function saveCategory($model, $team_id, $age) {

		$category_name = Utils::$categorias[$age];
		$category = Category::model()->findByAttributes(array('name'=>$category_name, 'team_id'=>$team_id));
		if($category == null) {
			$category = new Category();
			$category->name = $category_name; 
			$category->team_id = $team_id;
			$category->save();
		}
		
		return $category;
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Player']))
		{
			$model->attributes=$_POST['Player'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$player = new Player('search');
		$dataProvider = $player->search();
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Player('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Player']))
			$model->attributes=$_GET['Player'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Player::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='player-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	
}
